import React, { useState, useEffect } from 'react';
import axios from "../../../../../../util/axios";
import { Row, Col, Input, Button, Card, Table, Modal, message } from 'antd';
import Select from "./component/Select"
import ExportJsonExcel from 'js-export-excel'
import { ExclamationCircleOutlined } from '@ant-design/icons';
import XLSX from 'xlsx';
import "./index.css"
const { confirm } = Modal;
const Distribution = () => {
    const [list, setlist] = useState([]);
    const [dyType, setdyType] = useState('');
    const [val, setval] = useState('');
    let options4 = ['全部', '待付款', '待发货', '已发货', '已结算', '未结算'];
    const getList = async () => {
        let res = await axios.get('/orderdistribution');
        setlist(res.data.data)
    }
    useEffect(() => {
        getList()
    }, [])
    //打印类型
    const selectTimeType4 = async (e) => {
        console.log(dyType)
        setdyType(e)
        let res = await axios.get('/orderdistributionsou', {
            params: {
                sou: e
            }
        });
        setlist(res.data.data)
    }
    //设置input val
    const setVal = (e) => {
        setval(e.target.value)
    }
    //搜索 
    const searchList = async () => {
        let res = await axios.get('/orderdistributionsou', {
            params: {
                name: val
            }
        });
        setlist(res.data.data)
    }
    const columns = [
        {
            title: '选择',
            key: 'id',
            render: () => {
                return <input type="checkbox" />
            }
        },
        {
            title: '用户编号',
            key: 'id',
            dataIndex: 'userSerial',
        },
        {
            title: '姓名',
            key: 'id',
            dataIndex: 'name',
        },
        {
            title: '手机号',
            key: 'id',
            dataIndex: 'tel',
        },
        {
            title: '收货地址',
            key: 'id',
            dataIndex: 'address',
        },
        {
            title: '订单状态',
            key: 'id',
            dataIndex: 'orderState',
        },
        {
            title: '快递单号',
            key: 'id',
            dataIndex: 'orderSerial',
        },
        {
            title: '订单图片',
            key: 'id',
            render: (a, b) => {
                return <img src={b.orderImg} alt="" />
            }
        },
        {
            title: '订单规格',
            key: 'id',
            dataIndex: 'orderStyle',
        },
        {
            title: '宝贝数量',
            key: 'id',
            dataIndex: 'likeNum',
        },
        {
            title: '留言备注',
            key: 'id',
            dataIndex: 'text',
        },
        {
            title: '操作',
            key: 'id',
            render: (a, b) => {
                return <span onClick={() => { delItemList(b.id) }} style={{ color: 'red' }}>删除</span>
            }
        },
    ];

    const exportExcel = () => {
        const data1 = list //表格内部数据
        var option = {};
        let dataTable = [];
        if (data1) {
            for (let i in data1) {
                if (data1) {
                    let obj = {
                        'userSerial': data1[i].userSerial,
                        'name': data1[i].name,
                        'tel': data1[i].tel,
                        'address': data1[i].address,
                        'orderState': data1[i].orderState,
                        'orderSerial': data1[i].orderSerial,
                        'orderImg': data1[i].orderImg,
                        'orderStyle': data1[i].orderStyle,
                        'likeNum': data1[i].likeNum,
                        'text': data1[i].text,
                        'id': data1[i].id
                    }
                    dataTable.push(obj);
                }
            }
        }
        option.fileName = '订单数据'; //设置excel名称
        option.datas = [
            {
                sheetData: dataTable,
                sheetName: 'sheet',
                sheetFilter: ['userSerial', 'name', 'tel', 'address', 'orderState', 'orderSerial', 'orderImg', 'orderStyle', 'likeNum', 'text', 'id'],
                sheetHeader: ['userSerial', 'name', 'tel', 'address', 'orderState', 'orderSerial', 'orderImg', 'orderStyle', 'likeNum', 'text', 'id']
            }
        ];
        var toExcel = new ExportJsonExcel(option);
        toExcel.saveExcel();
    }
    const importExcel = (file) => {
        const { files } = file.target;

        // 通过FileReader对象读取文件

        const fileReader = new FileReader();

        fileReader.onload = event => {

            try {

                const { result } = event.target;

                // 以二进制流方式读取得到整份excel表格对象

                const workbook = XLSX.read(result, { type: 'binary' });

                // 存储获取到的数据

                let data = [];

                // 遍历每张工作表进行读取（这里默认只读取第一张表）

                for (const sheet in workbook.Sheets) {

                    // esline-disable-next-line

                    if (workbook.Sheets.hasOwnProperty(sheet)) {

                        // 利用 sheet_to_json 方法将 excel 转成 json 数据

                        data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));

                        // break; // 如果只取第一张表，就取消注释这行

                    }

                }
                // 最终获取到并且格式化后的 json 数据
                message.success('上传成功！')

                setlist(data)
            } catch (e) {
                // 这里可以抛出文件类型错误不正确的相关提示
                message.error('文件类型不正确！');
            }
        };

        // 以二进制方式打开文件

        fileReader.readAsBinaryString(files[0]);
    }
    function showDeleteConfirm() {
        return new Promise((res, rej) => {
            confirm({
                centered: true,
                closable: true,
                width: 600,
                title: '你确定要删除吗?',
                icon: <ExclamationCircleOutlined />,
                okText: '确定',
                okType: 'danger',
                cancelText: '取消',
                onOk() {
                    res()
                }
            });
        })
    }
    const delfunc = async (key) => {

        let result = await axios.get('/orderdistributionDel', { params: { id: key } })
        if (result.data.code === 200) {
            getList()
            message.success('删除成功');
        } else {
            message.success('删除失败');
        }
    }
    const delItemList = (key) => {
        showDeleteConfirm().then((res) => {
            delfunc(key)
        })
    }
    return (
        <div className='distribution'>
            <header>
                <h2>快递打印系统</h2>
            </header>
            <div className="selectFrom">
                <Row>
                    <Col span={20}>
                        <p>打印类型</p>
                        <Select options={options4} defaultValue={options4[0]} selectName={selectTimeType4}></Select>

                        <p> <Input placeholder='请输入关键字' value={val} onChange={setVal} /></p>
                        <Button type="primary" onClick={searchList}>
                            搜索
                        </Button>
                    </Col>
                </Row>
                <div className="site-card-border-less-wrapper">
                    <Card>
                        <div className="headTable">
                            <div className="orderTypes">
                                <p><span style={{ color: "skyblue" }}>订单情况：</span>xx买家/xx订单</p>
                                <p><span style={{ color: "skyblue" }}>快速模板：</span> <input type="radio" name='bendi' /> 本地配送</p>
                            </div>
                            <div className="orderBtn">
                                <div>
                                    <Button type="primary" onClick={exportExcel}>
                                        订单导出
                                    </Button>
                                </div>
                                <div>
                                    <div className="btnOut">
                                        <button className='bbttn'>导出订单</button>
                                        <input className='outE' type='file' accept='.xlsx, .xls' onChange={(e) => { importExcel(e) }} />
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="tableList">
                            <Table columns={columns} dataSource={list} rowKey='id' />
                        </div>
                    </Card>
                </div>
            </div>
        </div>
    );
}

export default Distribution;
